<?php

class Model_Agilet_Menu extends Model_Document
{

	/**
	 * @var string
	 */
	protected $_collection = 'agilet_menus';

	/**
	 * @param array $values
	 * @return Model_Agilet_Menu
	 */
	function editItem($values, $id = null)
	{
		if ($id == NULL)
		{
			$id = 'i' . Helper_String::randomString(5, 1);
		}

		$pid = $values['pid'];

		$item = array(
			'id' => $id,
			'pid' => $pid,
			'label' => $values['label'],
			'path' => $values['path'],
			'params' => array(),
			'type' => 'static',
			'position' => intval($values['position']),
			'active' => intval($values['active'])
		);

		$items = $this -> items;

		if ($pid == '')
		{
			$items[$id] = $item;
		}

		$this -> _set('items', $items);

		return $this;
	}

	public function getItem($id)
	{
		return $this -> _getItem($this -> items, $id);
	}

	protected function _getItem($items, $id)
	{
		foreach ($items as $key => $item)
		{
			if ($key == $id)
			{
				return $item;
			}
			if (isset($item['items']) && $items['items'])
			{
				$result = $this -> _getItem($item['items'], $id);
				if ($result)
				{
					return $result;
				}
			}
		}
		return array();
	}

	public function setItem($pid, $id, $data)
	{
		$items = $this -> items;

		if ($pid == '')
		{
			$items[$id] = $data;
		}
		else
		{
			$this -> _setItem($items, $pid, $id, $data);
		}

		$this -> _set('items', $items);

		return $this;
	}

	protected function _setItem(&$items, $pid, $id, $data)
	{
		foreach ($items as $key => $item)
		{
			if ($key == $id)
			{
				$items[$key] = $data;
			}
			else
			if (isset($item['items']) && $items['items'])
			{
				$this -> _setItem($items[$key]['items'], $pid, $id, $data);
			}
		}
	}

	public function deleteItem($id)
	{
		$items = $this -> items;
		$this -> _deleteItem($items, $id);
		$this -> _set('items', $items);
		return $this;
	}

	protected function _deleteItem(&$items, $id)
	{
		foreach ($items as $key => $item)
		{
			if ($key == $id)
			{
				unset($items[$key]);
				return;
			}
			else
			if (isset($item['items']) && $item['items'])
			{
				$this -> _deleteItem($items[$key]['items'], $id);
			}
		}
	}

}
